#!/bin/bash

# script to remove deleted hosts(those that don't exist in the config svn anymore)
# from configviewer
#
# * can be run standalone or via cron
# * take the filesystem path to the svn root as parameter
# 
#  configviewer-cleanup <PATH-TO-SVN-ROOT> 

# we want to terminate on any error
set -e


#
# local basic functions
#
function log {
    logger -t "$0" "$@"
    echo "$@"
}

function die {
    set +x
    exec 2>&3- # restore original STDERR
    logger -s -t "$0" "ERROR: $@"
    if [[ -r "$WORK/error.log" ]] ; then
        echo "ERROR LOG:"
        cat "$WORK/error.log"
    fi 1>&2
    exit 1
}

function cleanup {
    if [[ "${KEEPWORKDIR:=}" ]] ; then
        echo 1>&2 "Do not forget to remove the work dir '$WORK'"
    else
        rm -Rf "$WORK"
    fi
}

# get this from command line
[[ "$1" && -d "$1" && -r "$1/hooks/config_rpm_maker.conf" ]] || die "Must give path to svn repository with config_rpm_maker.conf on filesystem as parameter. Exiting."

WORK="$(mktemp -d -t "${0##*/}".XXXXXXXXXXXXXXX)"
trap cleanup 0
# store original STDERR in FD3
exec 3>&2 2>"$WORK/error.log" # collect all errors in log file
set -u -x # write command trace to log file and fail on empty variables

SVN_BASE_PATH="$1" ; shift

# required to source config file without an error
REPOS=""
# read configuration
source "$SVN_BASE_PATH/hooks/config_rpm_maker.conf"
if ! [[ "$CONFIG_VIEWER" && -d "$CONFIG_VIEWER/hosts" ]] ; then
    die "CONFIG_VIEWER not set or does not contain a hosts directory"
fi

svn ls "file://$SVN_BASE_PATH/config/host/" | sed -e 's#/##g' | sort >"$WORK/all_hosts_in_svn"
(( PIPESTATUS != 0 )) && die "svn ls failed" # check svn command for error

ls "$CONFIG_VIEWER/hosts/" | sort >"$WORK/all_hosts_in_configviewer" || die "could not read hosts in configviewer"

cd "$CONFIG_VIEWER/hosts/"

if join -v2 "$WORK/all_hosts_in_svn" "$WORK/all_hosts_in_configviewer" | xargs --no-run-if-empty rm -Rf ; then
    : succeed silently
else
    die "xargs rm failed"
fi

